﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Crm.SdkTypeProxy.Metadata;
using SalesTracker.Tools.EntityComparer.Lib;
using System.Web.Services.Protocols;
using System.Net;

namespace SalesTracker.Tools.EntityComparer
{
    public partial class EnitityComparerMain : Form
    {
        MetadataService LatestMetadataSvc = null;
        MetadataService OutdatedMetadataSvc = null;

        public EnitityComparerMain()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void txtLatestCrmUrl_TextChanged(object sender, EventArgs e)
        {
            if (txtLatestCrmUrl.Text.Length > 0)
            {
                var loginscreen = new LoginForm();
                loginscreen.txtUrl = txtLatestCrmUrl;
                loginscreen.MainForm = this;
                loginscreen.ShowDialog();

                txtOutdatedCrmEnvironmentUrl.ForeColor = Color.Black;
                txtOutdatedCrmEnvironmentUrl.BackColor = Color.White;
                txtOutdatedCrmEnvironmentUrl.Enabled = true;
                btnOutdatedUrlSettings.Enabled = true;
            }

        }

        private void txtOutdatedCrmEnvironmentUrl_TextChanged(object sender, EventArgs e)
        {
            if (SecondaryUrlCredentials != null)
            {
                txtOutdatedCrmEnvironmentUrl.BackColor = Color.Green;
                txtOutdatedCrmEnvironmentUrl.ForeColor = Color.White;
                return;
            }
            if (MessageBox.Show("You can use the same credentials as the Latest Environment Url.", "CRM Credentials", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == System.Windows.Forms.DialogResult.Yes)
            {

                SecondaryUrlCredentials = PrimaryUrlCredentials;

                txtOutdatedCrmEnvironmentUrl.BackColor = Color.Green;
                txtOutdatedCrmEnvironmentUrl.ForeColor = Color.White;
                return;
            }
            else
            {
                if (txtOutdatedCrmEnvironmentUrl.Text.Length > 0)
                {
                    var loginscreen = new LoginForm();
                    loginscreen.txtUrl = txtOutdatedCrmEnvironmentUrl;
                    loginscreen.MainForm = this;
                    loginscreen.ShowDialog();

                    if (OutdatedMetadataSvc == null)
                    {
                        if (SecondaryUrlCredentials != null)
                        {
                            var metadatasrvadapter = new CrmMetadataServiceAdapter(txtOutdatedCrmEnvironmentUrl.Text);
                            OutdatedMetadataSvc = metadatasrvadapter.NewCrmservice(SecondaryUrlCredentials);
                        }
                    }
                }
            }
        }

        private void btnLatestUrlSettings_Click(object sender, EventArgs e)
        {
            if (txtLatestCrmUrl.Text.Length > 0)
            {
                var loginscreen = new LoginForm();
                loginscreen.txtUrl = txtLatestCrmUrl;
                loginscreen.MainForm = this;
                loginscreen.ShowDialog();
            }
            else
            {
                MessageBox.Show("Please complete the enviroment url to setup");
            }
        }

        private void btnOutdatedUrlSettings_Click(object sender, EventArgs e)
        {
            if (txtOutdatedCrmEnvironmentUrl.Text.Length > 0)
            {
                var loginscreen = new LoginForm();
                loginscreen.txtUrl = txtOutdatedCrmEnvironmentUrl;
                loginscreen.MainForm = this;
                loginscreen.ShowDialog();
            }
            else
            {
                MessageBox.Show("Please complete the enviroment url to setup");
            }
        }

        public System.Net.NetworkCredential PrimaryUrlCredentials { get; set; }

        public System.Net.NetworkCredential SecondaryUrlCredentials { get; set; }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {

                if (PrimaryUrlCredentials == null)
                {
                    if (txtLatestCrmUrl.Text.Length > 0)
                    {
                        txtLatestCrmUrl.BackColor = Color.Red;
                        var loginscreen = new LoginForm();
                        loginscreen.txtUrl = txtLatestCrmUrl;
                        loginscreen.MainForm = this;
                        loginscreen.ShowDialog();
                    }
                }
                if (PrimaryUrlCredentials == null)
                {
                    return;
                }

                if (SecondaryUrlCredentials == null)
                {
                    if (txtOutdatedCrmEnvironmentUrl.Text.Length > 0)
                    {
                        txtOutdatedCrmEnvironmentUrl.BackColor = Color.Red;
                        var loginscreen = new LoginForm();
                        loginscreen.txtUrl = txtOutdatedCrmEnvironmentUrl;
                        loginscreen.MainForm = this;
                        loginscreen.ShowDialog();
                    }
                }
                if (SecondaryUrlCredentials == null)
                {
                    return;
                }

            var metadatasrvadapter = new CrmMetadataServiceAdapter(txtLatestCrmUrl.Text);
            LatestMetadataSvc = metadatasrvadapter.NewCrmservice(PrimaryUrlCredentials);



            metadatasrvadapter = new CrmMetadataServiceAdapter(txtOutdatedCrmEnvironmentUrl.Text);
            OutdatedMetadataSvc = metadatasrvadapter.NewCrmservice(SecondaryUrlCredentials);


            var comparer = new EntityComparer.Lib.EntityComparer();

            if (!ValidateInput())
            {
                return;
            }

          
                string entityname = string.Empty;

                if (comboBEntityCompare.Items.Count == 0)
                {
                    entityname = comboBEntityCompare.Text;
                }
                else
                {
                    entityname = comboBEntityCompare.SelectedValue.ToString();
                }
                var attributesnotfound = comparer.CompareAttributes(LatestMetadataSvc, OutdatedMetadataSvc, entityname);
                dataGridView1.AutoGenerateColumns = false;
                dataGridView1.DataSource = attributesnotfound;

                if (attributesnotfound.Count == 0)
                {
                    MessageBox.Show("The two entities have the same attributes in the two environments.");
                }

            }
            catch (SoapException exc)
            {
                MessageBox.Show(string.Format("{0} on the outdated environment.", exc.Detail.SelectSingleNode("//description").InnerText));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private bool ValidateInput()
        {

            if (txtOutdatedCrmEnvironmentUrl.Text.Length == 0 && txtLatestCrmUrl.Text.Trim().Length == 0)
            {
                txtLatestCrmUrl.BackColor = Color.Red;
                txtLatestCrmUrl.ForeColor = Color.White;
                txtOutdatedCrmEnvironmentUrl.BackColor = Color.Red;
                txtOutdatedCrmEnvironmentUrl.ForeColor = Color.White;
                MessageBox.Show("Please make sure the fieldS in red background are completed with correct values");
                return false;
            }

            if (txtLatestCrmUrl.Text.Trim().Length == 0)
            {
                txtLatestCrmUrl.BackColor = Color.Red;
                txtLatestCrmUrl.ForeColor = Color.White;
                MessageBox.Show("Please make sure the field in red background is completed with correct value");
                return false;
            }
            if (txtOutdatedCrmEnvironmentUrl.Text.Length == 0)
            {
                txtOutdatedCrmEnvironmentUrl.BackColor = Color.Red;
                txtOutdatedCrmEnvironmentUrl.ForeColor = Color.White;
                MessageBox.Show("Please make sure the field in red background is completed with correct value");
                return false;
            }

            return true;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {


                var createattributes = new List<EntityAttributes>();
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    var addtocreate = (DataGridViewCheckBoxCell)row.Cells[0];
                    if (bool.Parse(addtocreate.FormattedValue.ToString()) && (!row.ReadOnly))
                    {
                        createattributes.Add((EntityAttributes)row.DataBoundItem);
                        row.DefaultCellStyle.BackColor = Color.Gray;
                        row.ReadOnly = true;

                    }
                }

                var comparer = new EntityComparer.Lib.EntityComparer();
                comparer.CreateAttributes(OutdatedMetadataSvc, createattributes);

                if (createattributes.Count > 0)
                {
                    MessageBox.Show("All selected attributes are created in the new environment.");
                }
            }
            catch (SoapException sexcept)
            {
                MessageBox.Show(string.Format("{0}.", sexcept.Detail.SelectSingleNode("//description").InnerText));
            }

        }

        private void btnFetch_Click(object sender, EventArgs e)
        {

            if (txtLatestCrmUrl.Text.Length == 0)
            {
                MessageBox.Show("Please complete the Lastest Environment URL field");
                return;
            }



            if (PrimaryUrlCredentials == null)
            {
                if (txtLatestCrmUrl.Text.Length > 0)
                {
                    var loginscreen = new LoginForm();
                    loginscreen.txtUrl = txtLatestCrmUrl;
                    loginscreen.MainForm = this;
                    loginscreen.ShowDialog();
                }
            }
            if (PrimaryUrlCredentials == null)
            {
                return;
            }
            btnFetch.Text = "Working..";
            btnFetch.Enabled = false;

            try
            {

              
                    var metadatasrvadapter = new CrmMetadataServiceAdapter(txtLatestCrmUrl.Text);
                    LatestMetadataSvc = metadatasrvadapter.NewCrmservice(PrimaryUrlCredentials);
                

                var comparer = new EntityComparer.Lib.EntityComparer();
                var entities = comparer.GetAllEntities(LatestMetadataSvc);
                comboBEntityCompare.Items.Clear();

                comboBEntityCompare.DisplayMember = "DisplayName";
                comboBEntityCompare.ValueMember = "Value";

                comboBEntityCompare.DataSource = entities;
                if (entities.Count > 0)
                {
                    txtOutdatedCrmEnvironmentUrl.ForeColor = Color.Black;
                    txtOutdatedCrmEnvironmentUrl.BackColor = Color.White;
                    txtOutdatedCrmEnvironmentUrl.Enabled = true;
                    btnOutdatedUrlSettings.Enabled = true;
                }
            }
            catch (Exception exc)
            {

                MessageBox.Show(exc.Message);
            }
            finally
            {
                btnFetch.Text = "Fetch";
                btnFetch.Enabled = true;
            }


        }
    }
}
